<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /*
      思路：定义一个栈，存放所有数字，遇到了符号，那么区分符号，如果之前的是+，就将count推入,保障栈里所有元素
      最后相加(这是因为没有括号的原因，只需要遇到乘除的时候取栈顶元素即可)

      15+3 * 2 +
      */
      var calculate = function (s) {
        s = s + '+'
        let pre = '+'
        let count = 0
        const stack = []
        for (let i = 0; i < s.length; i++) {
          if (s[i] == ' ') continue
          //可能遇到超过10以上的数字，需要进行存储
          if (+s[i] >= 0 && +s[i] <= 9) {
            count = count * 10 + +s[i]
          } else {
            switch (pre) {
              case '+':
                stack.push(count)
                break
              case '-':
                stack.push(-count)
                break
              case '*':
                let tail = stack.pop()
                stack.push(tail * count)
                break
              case '/':
                let tail2 = stack.pop()
                stack.push(parseInt(tail2 / count))
                break
            }
            pre = s[i]
            count = 0
          }
        }
        return stack.reduce((pre, item) => (pre += item), 0)
      }

      var calculate2 = function (s) {
        //复杂计算器思路：遇到了非右括号就入栈，遇到了右括号，就找最近的左括号，拼接括号内部字符，然后计算，重新推入栈中
        const stack = []
        let tempStr = ''
        for (let i = 0; i < s.length; i++) {
          if (s[i] == ' ') continue
          if (s[i] != ')') {
            stack.push(s[i])
          } else {
            //遇到了右括号，那么找出最近的左括号  (2+4*2)
            let tailChar = stack[stack.length - 1]
            while (tailChar != '(') {
              tempStr = stack.pop() + tempStr
              tailChar = stack[stack.length - 1]
            }
            //遇到左括号
            stack.pop()
            stack.push(calculate(tempStr))
            tempStr = ''
          }
        }
        return calculate(stack.join(''))
      }
      console.log(calculate2('(1+(4+5-2)*2)+(6*8)'))
      console.log(1 + (4 + 5 - 2) * 2 + 6 * 8)
    </script>
  </body>
</html>
